# -*- coding: utf-8 -*-
#!/usr/bin/python
import re
import random
from sympy import solve, Symbol


#sign=['+','-','/']
sign = ['/', '/', '/']
var = ['a', 'b']


def pa_solve(eq, var='x'):
    eql = eq.replace("=", "-(") + ")"
    print eql
    c = eval(eql, {var: 1j})
    print c
    if c.imag > 1:
        result = str(-c.real / c.imag)
        if not re.match(r'-', result) and re.match(r'.*\.0$', result):
            return eq.replace("*x", "x").replace("1x", "x"), result
def genEqutionsFromFile():
    with open('mathtest/mathutils/source.txt','r') as source:
        x = Symbol('x')
        eqs=[]
        for line in source:
            save_eq=line.strip()
            eq=line.strip().replace("(","*(").replace('x','*x').replace("=", "-(") + ")"
            r = re.match(r'.*(\D)\*x.*', eq)
            if r:
                eq=re.sub(r'\D\*x',r.group(1)+'x',eq)
            r=re.match(r'.*(\D)\*\(.*', eq)
            if r:
                eq=re.sub(r'\D\*\(',r.group(1)+'(',eq)
            if not re.match(r'\-.*|.*/.*',str(solve(eq)[0])):
                eqs.append((save_eq,solve(eq)[0],2))
    return eqs

def genEqutions(len=100):
    results = []
    for i in range(1, 1000):
        a = random.randint(1, 50)
        s = sign[random.randint(0, 2)]
        b = "%s*x" % (random.randint(2, 10))
        c = random.randint(1, 100)
        em = random.randint(0, 1)
        # eql="(%s) %s (%s) = %s"%(eval(var[em]),s,eval(var[1-em]),c)
        eql = "(%s) %s (%s) = %s" % (a, s, b, c)
        save_eql="%s %s %s = %s" % (a, s, b, c)
        save_eql=save_eql.replace('/','÷').replace("*x","x").replace("1x","x")
        new_eql = eql.replace("=", "-(") + ")"
        x = Symbol('x')
        result = str(solve(new_eql)[0])
        m = re.compile(r'-.*|.*/.*|0')
        if not m.match(result):
            results.append((save_eql, result,1))
            #print save_eql
    trancat_results = results[0:len]
    return trancat_results


genEqutionsFromFile()

